package com.wjh.web;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.commons.collections4.MapUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson2.JSON;
import com.wjh.base.ResponseApiCode;
import com.wjh.base.ResponseApiData;
import com.wjh.common.BaseInfo;
import com.wjh.common.LockConstant;
import com.wjh.pay.request.PayOrderRequest;
import com.wjh.serivce.IPayService;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;

/**
 * 支付 AIP接口
 * 
 * @author wenjianhai
 * @date 2023/6/24
 * @since JDK 17
 */
@Tag(name = "支付 AIP接口", description = "支付 AIP接口")
@Slf4j
@RestController
@RequestMapping("/pay")
public class PayController extends BaseController {

	@Autowired
	private IPayService payService;

	@Autowired
	private RedissonClient redissonClient;

	@Operation(summary = "订单支付", description = "订单支付")
	// @AccessLimit(maxCount = 3, second = 60) // 限流 : 60秒钟内最多允许调用3次
	@PostMapping("/order")
	public ResponseApiData<?> payOrder(@Validated @RequestBody PayOrderRequest request) {
		log.info("订单支付-开始.请求参数:{}", JSON.toJSONString(request));
		// 当前登录人
		BaseInfo baseInfo = this.getBaseInfo();
		// 分布式锁
		RLock lock = null;

		try {
			String rdsKey = String.format(LockConstant.PAY_ORDER_LOCK_NAME, request.getOrderGuid(),
					baseInfo.getUserGuid());
			// 分布式锁
			lock = redissonClient.getLock(rdsKey);

			if (!lock.tryLock(LockConstant.PAY_ORDER_LOCK_WAIT_TIME, LockConstant.PAY_ORDER_LOCK_LEASE_TIME,
					TimeUnit.SECONDS)) {
				log.info("订单支付,获取锁失败.rdsKey:{}", rdsKey);
				if (lock.isLocked()) {
					lock.unlock();
				}
				return ResponseApiData.fail(ResponseApiCode.REPEAT_OPT.getCode(), ResponseApiCode.REPEAT_OPT.getMessage());
			}
			return payService.payOrder(request, baseInfo);
		} catch (Exception e) {
			log.error(String.format("订单支付-失败.请求参数:%s", JSON.toJSONString(request)), e);
			return ResponseApiData.systemFail(e.getMessage());
		} finally {
			if (lock != null && lock.isLocked()) {
				lock.unlock();
			}
		}
	}

	@Operation(summary = "订单支付回调", description = "订单支付回调")
	@PostMapping("/callback")
	public ResponseApiData<?> callback(HttpServletRequest request) {
		log.info("订单支付回调-开始");
		// 获取支付宝POST过来反馈信息（回调参数）
		Map<String,String[]> requestParams = null;

		try {
			// 获取支付宝POST过来反馈信息
			requestParams = request.getParameterMap();

			if (MapUtils.isEmpty(requestParams)) {
				log.info("订单支付回调,回调参数为空");
				return ResponseApiData.parameterFail("回调参数为空");
			}
			payService.callback(requestParams);

			log.info("订单支付回调-结束.回调参数:{}", JSON.toJSONString(requestParams));

			return ResponseApiData.success();
		} catch (Exception e) {
			log.error(String.format("订单支付回调-失败.回调参数:%s", JSON.toJSONString(requestParams)), e);
			return ResponseApiData.systemFail(e.getMessage());
		}
	}
}
